package pl.droidsonroids.gif;

import ohos.agp.components.element.Element;
import ohos.utils.Parcel;
import ohos.utils.Sequenceable;

/**
 * GifViewSavedState
 */
public class GifViewSavedState extends BaseSavedState {
    /**
     * Creator instance
     */
    public static final Producer<GifViewSavedState> CREATOR = new Producer<GifViewSavedState>() {
        /**
         * Creates saved state from parcel
         * @param in parcel
         * @return saved state
         */
        public GifViewSavedState createFromParcel(Parcel in) {
            return new GifViewSavedState(in);
        }

        /**
         * Array of saved states
         * @param size size
         * @return saved state array
         */
        public GifViewSavedState[] newArray(int size) {
            return new GifViewSavedState[size];
        }
    };

    final long[][] mStates;

    GifViewSavedState(Sequenceable superState, Element... drawables) {
        super(superState);
        mStates = new long[drawables.length][];
        for (int i = 0; i < drawables.length; i++) {
            Element drawable = drawables[i];
            if (drawable instanceof GifDrawable) {
                mStates[i] = ((GifDrawable) drawable).mNativeInfoHandle.getSavedState();
            } else {
                mStates[i] = null;
            }
        }
    }

    private GifViewSavedState(Parcel in) {
        super(in);
        mStates = new long[in.readInt()][];
        for (int i = 0; i < mStates.length; i++)
            mStates[i] = new long[in.getSize()];
    }

    GifViewSavedState(Sequenceable superState, long[] savedState) {
        super(superState);
        mStates = new long[1][];
        mStates[0] = savedState;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeInt(mStates.length);
        for (long[] mState : mStates)
            dest.writeLongArray(mState);
    }

    void restoreState(Element drawable, int index) {
        if (mStates[index] != null && drawable instanceof GifDrawable) {
            final GifDrawable gifDrawable = (GifDrawable) drawable;
            gifDrawable.startAnimation(gifDrawable.mNativeInfoHandle.restoreSavedState(mStates[index],
                gifDrawable.mPixelMap));
        }
    }
}
